//
//  NSString+GString.m
//  KingDraw
//
//  Created by Mask on 2018/5/16.
//  Copyright © 2018年 Mask. All rights reserved.
//

#import "NSString+GString.h"


@implementation NSString (GString)



+(BOOL)isValidateMobile:(NSString *)mobile{
    //手机号以13， 15，18 14 17开头，八个 \d 数字字符      NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSString *phoneRegex = @"^((13[0-9])|(15[0-9])|(18[0-9])|(17[0-9])|(14[0-9])|(16[0-9])|(19[0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

+(BOOL)CheckPassWordInput:(NSString *)password{
    /// ^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$
    NSString *pattern = @"^[^\u4e00-\u9fa5]{6,16}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}

///
+(BOOL)CheckEmilIsAvaliable:(NSString *)password{
    /// ^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$
    NSString *pattern = @"\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}

//动态计算高度
+ (CGSize)workOutSizeWithStr:(NSString *)str andFont:(NSInteger)fontSize value:(NSValue *)value{
    if (!str) {
        str = @"";
    }
    CGSize size = CGSizeMake(0, 0);
    if (str) {
        if (SYSTEM_VERSIONS>=7.0) {
            NSDictionary *attribute = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil];
            size=[str boundingRectWithSize:[value CGSizeValue] options:NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingTruncatesLastVisibleLine attributes:attribute context:nil].size;
        }
    }
    
    return size;
}

+ (CGSize)workOutSizeWithStr:(NSString *)str andFont:(NSInteger)fontSize value:(NSValue *)value lineSpace:(CGFloat)lineSpace{
    if (!str) {
        str = @"";
    }
    CGSize size = CGSizeMake(0, 0);
    if (str) {
        if (SYSTEM_VERSIONS>=7.0) {
            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
            paragraphStyle.lineSpacing = lineSpace;
            paragraphStyle.lineBreakMode=NSLineBreakByCharWrapping;
            NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize], NSParagraphStyleAttributeName:paragraphStyle};
            size=[str boundingRectWithSize:[value CGSizeValue] options:NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingTruncatesLastVisibleLine attributes:dict context:nil].size;
        }
    }
    
    return size;
}

/**
 字符串部分字符修改颜色
 
 @param setStr 要设置的字符串
 @param content content
 @param color 颜色
 @return NSMutableAttributedString
 */
+ (NSMutableAttributedString *)setToStr:(NSString *)setStr content:(NSString *)content Color:(UIColor *)color font:(int)font {
    NSMutableAttributedString * AttributedStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange range = NSMakeRange(0, 0);
    if (setStr.length>0 && setStr != nil) {
        range = [content rangeOfString:setStr];
    }
    [AttributedStr addAttribute:NSForegroundColorAttributeName value:color range:range];
    [AttributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font] range:NSMakeRange(0, content.length)];
    return AttributedStr;
}

/**
 指定 字符 变色
 
 @param content 显示的所有内容
 @param keys 需要改变颜色的 字符数组
 @param changeColor 需要改变的颜色
 @return NSMutableAttributedString
 */
+ (NSMutableAttributedString *)allContent:(NSString *)content keys:(NSArray<NSString *>*)keys changeColor:(UIColor *)changeColor {
    NSMutableAttributedString * attributed =[[NSMutableAttributedString alloc] initWithString:content];
    NSMutableArray * rangeValues = [NSMutableArray array];
    for (NSString * key in keys) {
        NSRange range =[content rangeOfString:key];
        NSValue * value = [NSValue valueWithRange:range];
        [rangeValues addObject:value];
    }
    for (NSValue * rangeValue in rangeValues) {
        NSRange range =[rangeValue rangeValue];
        [attributed addAttribute:NSForegroundColorAttributeName value:changeColor range:range];
    }
    return attributed;
}

/**
 去空格
 
 @param string string
 @return string
 */
+ (NSString *)deleteSpaceWithString:(NSString *)string {
    NSArray * textArray = [string componentsSeparatedByString:@" "];//利用空格转数组去空格
    NSMutableString * newStr = [[NSMutableString alloc] init];
    for (NSString * str in textArray) {
        [newStr appendString:str];
    }
    return newStr;
}

/**
 验证字符串是否为汉字

 @param str str
 @return BOOL
 */
+(BOOL)isChineseCharacters:(NSString *)str {
    //是否以中文开头(unicode中文编码范围是0x4e00~0x9fa5)
    int utfCode = 0;
    void *buffer = &utfCode;
    NSRange range = NSMakeRange(0, 1);
    //判断是不是中文开头的,buffer->获取字符的字节数据 maxLength->buffer的最大长度 usedLength->实际写入的长度，不需要的话可以传递NULL encoding->字符编码常数，不同编码方式转换后的字节长是不一样的，这里我用了UTF16 Little-Endian，maxLength为2字节，如果使用Unicode，则需要4字节 options->编码转换的选项，有两个值，分别是NSStringEncodingConversionAllowLossy和NSStringEncodingConversionExternalRepresentation range->获取的字符串中的字符范围,这里设置的第一个字符 remainingRange->建议获取的范围，可以传递NULL
    BOOL b = [str getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];
    if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5))
        return YES;
    else
        return NO;
}

- (int)includeChinese
{
    int cCount=0;
    for(int i=0; i< [self length];i++)
    {
        int a =[self characterAtIndex:i];
        if( a >0x4e00&& a <0x9fff){
            cCount+=1;
        }
    }
    return cCount;
}


///通过字节计算文件大小
+ (NSString *)setFileSize:(CGFloat)fileSize {
    NSString * fileSizeStr;
    if (fileSize<1024) {
        fileSizeStr=[NSString stringWithFormat:@"%.0f B",fileSize];
    }else{
        CGFloat kb=fileSize/1024;
        if (kb<1024) {
            fileSizeStr=[NSString stringWithFormat:@"%.0f KB",kb];
        }else{
            CGFloat mb=kb/1024;
            if (mb<1024) {
                fileSizeStr=[NSString stringWithFormat:@"%.2f MB",mb];
            }else{
                fileSizeStr=[NSString stringWithFormat:@"%.2f GB",mb/1024];
            }
        }
    }
    return fileSizeStr;
}

// https://www.jianshu.com/p/1b3ecbc9b5c1
// 使用GBK的编码，去判断用户输入的字符个数
- (NSUInteger)charactorNumber {
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    return [self charactorNumberWithEncoding:encoding];
}

- (NSUInteger)charactorNumberWithEncoding:(NSStringEncoding)encoding {
    NSUInteger strLength = 0;
    char *p = (char *)[self cStringUsingEncoding:encoding];
    NSUInteger lengthOfBytes = [self lengthOfBytesUsingEncoding:encoding];
    for (int i = 0; i < lengthOfBytes; i++) {
        if (*p) {
            p++;
            strLength++;
        }
        else {
            p++;
        }
    }
    return strLength;
}
@end
